package com.demo;

import com.google.gson.internal.bind.util.ISO8601Utils;
import io.github.bonigarcia.wdm.WebDriverManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class AutoTests {
    static DriverConfig driverConfig = new DriverConfig();
//    static WebDriver driver = driverConfig.getChromeDriver(List.of("--headless"));
    static WebDriver driver = driverConfig.getChromeDriver();
    static WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));


    public static void main1(String[] args) throws Exception {
        AutoTests autoTests = new AutoTests();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        autoTests.login();

        System.out.println("======创建奖品========");
        List<PrizeInfo> prizes = autoTests.getPrizes();
        System.out.println(Arrays.toString(prizes.toArray()));

        autoTests.createPrize();

        prizes = autoTests.getPrizes();
        System.out.println(Arrays.toString(prizes.toArray()));

        System.out.println("======创建用户========");
        List<UserInfo> users = autoTests.getUsers();
        System.out.println(Arrays.toString(users.toArray()));

        autoTests.createUser();

        users = autoTests.getUsers();
        System.out.println(Arrays.toString(users.toArray()));

        System.out.println("======创建活动========");
        autoTests.createActive();

        List<ActivityInfo> activeList = autoTests.getActiveList();
        System.out.println(activeList);

        autoTests.getScreenshot();
        driver.quit();
        System.out.println("普通测试完成");
//        autoTests.switchWindow();
    }

    public static void main(String[] args) {
        AutoTests autoTests = new AutoTests();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        autoTests.login();

        autoTests.createActive();
//        autoTests.drawPrize();
    }

    //*[@id="activities"]/div[1]/div[2]/p/a
    void drawPrize() {
        try{
            driver.switchTo().defaultContent();

            driver.findElement(By.cssSelector("#activitiesList")).click();

            driver.switchTo().frame("contentFrame");

            String href = driver.findElement(By.cssSelector("#activities > div:nth-child(1) > div.active > p > a")).getAttribute("href");

            driver.get(href);

            driver.findElement(By.cssSelector("#container > div.opt-box > span.btn.next-btn")).click();

            Thread.sleep(100);

            driver.findElement(By.cssSelector("#container > div.opt-box > span.btn.next-btn")).click();

            String luckyMan = driver.findElement(By.cssSelector("#list > span")).getText();

            log.info("中奖人是:"+ luckyMan);

            driver.findElement(By.cssSelector("#container > div.opt-box > span.btn.next-btn")).click();

            driver.close();
        }catch (Exception e){
            log.error(e.getMessage(), e);
            log.error("抽奖测试失败");
            getScreenshot("drawPrize_error");
        }
    }

    List<ActivityInfo> getActiveList() {
        try {
            driver.switchTo().defaultContent();

            driver.findElement(By.cssSelector("#activitiesList")).click();

            wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("contentFrame"));

            List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"activities\"]/div"));

            List<String> collect = elements.stream().map(WebElement::getText).collect(Collectors.toList());

            log.info("获取活动列表成功");

            List<ActivityInfo> ret = new LinkedList<>();
            for (String s : collect) {
                String[] split = s.split("\n");
                ActivityInfo activityInfo = new ActivityInfo(split[0], split[1], split[2]);
                ret.add(activityInfo);
            }

            return ret;

        }catch (Exception e) {
            log.error(e.getMessage(), e);
            log.error("获取活动列表失败");
            getScreenshot();
            return null;
        }
    }

    void createActive() {
        try {
            driver.switchTo().defaultContent();

            driver.findElement(By.cssSelector("#createActivity")).click();

            wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("contentFrame"));

            driver.findElement(By.cssSelector("#activityName")).sendKeys(UUID.randomUUID().toString().substring(0, 10));

            driver.findElement(By.cssSelector("#description")).sendKeys("auto test"+UUID.randomUUID().toString().replace("-", ""));

            //圈选user
            int users = choiceActiveUser();

            //圈选奖品
            choiceActivePrize(users);

            //提交
            driver.findElement(By.cssSelector("#createActivity")).click();

            wait.until(ExpectedConditions.alertIsPresent());

            String text = driver.switchTo().alert().getText();

            if(!"创建成功!".equals(text)) {
                throw new Exception(text);
            }
            driver.switchTo().alert().accept();
            log.info("活动创建成功");
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            log.error("创建抽奖活动失败");
            getScreenshot();
        }
    }

    void choiceActivePrize(int users) {
        driver.findElement(By.cssSelector("#buttonPrizes")).click();

        List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"prizesContainer\"]/div"));

        int size = elements.size();

        int times  = users / 4 + 1;

        System.out.println("size = " + size);

        System.out.println("users = " + users);
        System.out.println("times = " + times);

        //随机选择奖品
        for(int i = 0; i < times; i++) {
            int index = new Random().nextInt(1, size);
            driver.findElement(By.xpath("//*[@id=\"prizesContainer\"]/div[" + index + "]/input[@type='checkbox']")).click();

            //*[@id="prizesContainer"]/div[1]/select/option[3]
            int tire = new Random().nextInt(1, 4);
            driver.findElement(By.xpath("//*[@id=\"prizesContainer\"]/div[" + index + "]/select/option["+tire+"]")).click();

            //设置数量
            int i1 = new Random().nextInt(1, 5);
            driver.findElement(By.xpath("//*[@id=\"prizesContainer\"]/div[" + index + "]/input[@class='form-control']")).clear();

            driver.findElement(By.xpath("//*[@id=\"prizesContainer\"]/div[" + index + "]/input[@class='form-control']")).sendKeys(i1 + "");
        }

        //确定
        driver.findElement(By.cssSelector("#prizesModal > div > div.form-btn-box > button.btn.btn-primary")).click();

    }

    int choiceActiveUser() {
        driver.findElement(By.cssSelector("#buttonUsers")).click();

        List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"usersContainer\"]/div"));

        int size = elements.size();

        int times = new Random().nextInt(15, size);

        times = times / 10 == 0 ? times * 2 : times;

        //随机选择人
        for(int i = 0; i < times; i++) {
            int index = new Random().nextInt(1, size);
            driver.findElement(By.xpath("//*[@id=\"usersContainer\"]/div["+index+"]/input[@type='checkbox']")).click();
        }

        driver.findElement(By.cssSelector("#usersModal > div > div.form-btn-box > button.btn.btn-primary")).click();

        return times;
    }

    void createUser() {
        try {
            driver.switchTo().defaultContent();

            driver.findElement(By.cssSelector("#register")).click();

            wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("contentFrame"));

            driver.findElement(By.cssSelector("#name")).sendKeys((UUID.randomUUID()+"").substring(0, 10));

            driver.findElement(By.cssSelector("#mail")).sendKeys((UUID.randomUUID().toString().replace("-", "").substring(1, 15) + "@163.com"));

            driver.findElement(By.cssSelector("#registerForm > button")).click();

            log.info("普通创建用户成功");
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            log.error("创建用户失败");
            getScreenshot();
        }
    }

    List<PrizeInfo> getPrizes() {
        try {
            driver.switchTo().defaultContent(); //那就是最开头的哪一层吧

            driver.findElement(By.cssSelector("body > div.cont-box > div.sidebar > ul > li:nth-child(2) > ul > li:nth-child(1) > a")).click();
            //页面中有iframe的处理方式
            wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("contentFrame"));
//            driver.switchTo().frame("contentFrame");
            // 这一步就定位了。并且已经定位到了
            List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"prizeList\"]/tr"));

            //这个是有什么影响吗 --- 你注意看你的报错信息， 是找不到元素，你上调试到这个elems的时候，已经获取到了元素，说明已经定位到了
            // 然后你下一步切换到上一个frame 已经定位到了元素了就不用在切换。反而是 切出去了。所以找不到
            // 我切出去了但是没有定位元素的嘛 -- 可以这么说。是因为你切出去了。 所以找不到然后报错

            //这里切出去了 但是找元素是在上面就找好了吧 感觉还是有点神奇 我手动这样切出去了这个driver是在哪里起作用，上一层的iframe
            log.info("获取奖品信息成功");

            List<String> collect = elements.stream().map(WebElement::getText).toList();

            List<PrizeInfo> ret = new LinkedList<>();

            for (String s : collect) {
                String[] split = s.split(" ");
                PrizeInfo prizeInfo = new PrizeInfo(split[0], split[1], split[2], split[3]);
                ret.add(prizeInfo);
            }

            return ret;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            System.out.println("获取奖品信息异常退出");
            getScreenshot();
            return null;
        }
    }

    List<UserInfo> getUsers(){
        try{
            driver.switchTo().defaultContent();

            driver.findElement(By.cssSelector("#userList")).click();

            wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("contentFrame"));
//            driver.switchTo().frame("contentFrame");

            List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"userList\"]/tr"));

            List<String> collect = elements.stream().map(WebElement::getText).collect(Collectors.toList());

//            driver.switchTo().parentFrame(); //这样切出去可能不会保证作用在最初的页面

            List<UserInfo> ret = new LinkedList<>();

            for (String s : collect) {
                String[] split = s.split(" ");
                UserInfo userInfo = new UserInfo(split[0], split[1], split[2]);
                ret.add(userInfo);
            }

            log.info("成功获取到用户列表");

            return ret;
        }catch (Exception e){
            log.error(e.getMessage());
            System.out.println("获取用户信息异常退出");
            getScreenshot(driver);
            driver.quit();
            return null;
        }
    }

    void createPrize(){
        try{
            driver.switchTo().defaultContent();

            driver.findElement(By.cssSelector("body > div.cont-box > div.sidebar > ul > li:nth-child(2) > ul > li:nth-child(2) > a")).click();

            driver.switchTo().frame("contentFrame");

            driver.findElement(By.cssSelector("#prizeName")).sendKeys("auto" + UUID.randomUUID().toString().replace("-", "").substring(0, 10));

            driver.findElement(By.cssSelector("#prizeImageUrl")).sendKeys("C:\\Users\\15328\\Downloads\\20250425014617174551677733166.jpg");

            driver.findElement(By.cssSelector("#price")).sendKeys("666");

            driver.findElement(By.cssSelector("#description")).sendKeys("这是一个测试");

            driver.findElement(By.cssSelector("body > div > button")).click();

            wait.until(ExpectedConditions.alertIsPresent());

            driver.switchTo().alert().accept();

            System.out.println("成功注册奖品");
        }catch (Exception e){
            log.error(e.getMessage());
            System.out.println("创建奖品异常退出");
            getScreenshot(driver);
            driver.quit();
        }
    }

    void login(){
//        WebDriver driver = driverConfig.getChromeDriverSystem();
        try {
            driver.navigate().to("http://127.0.0.1:8080/blogin.html");

            driver.findElement(By.cssSelector("#phoneNumber")).sendKeys("hadage");

            driver.findElement(By.cssSelector("#password")).sendKeys("hadage");

            driver.findElement(By.cssSelector("#loginForm > button")).click();

            System.out.println("成功登录");

        }catch (Exception e) {
            log.error(e.getMessage());
            System.out.println("异常退出");
            getScreenshot(driver);
            driver.quit();
        }
    }

    void alter() {
//        //回退
//        driver.navigate().back();
//        //前进
//        driver.navigate().forward();
//        //刷新
//        driver.navigate().refresh();
        //弹窗
//        Alert alert = driver.switchTo().alert();
//        //同意 弹窗
//        alert.accept();
//        //拒绝
//        alert.dismiss();
//        //设置弹窗内容
//        alert.sendKeys("");
//        alert.sendKeys("");
        }
    void getScreenshot(String msg) {
        try {
            File f = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf2 = new SimpleDateFormat("HH-mm-ss-SS");

            String format = sdf.format(new Date());
            String format1 = sdf2.format(new Date());

            System.out.println("src/pic/" + format + format1 + ".png");
            FileUtils.copyFile(f, new File("src/pic/" + format + "/" + msg + format1 + ".png"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    void getScreenshot() {
        try {
            File f = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf2 = new SimpleDateFormat("HH-mm-ss-SS");

            String format = sdf.format(new Date());
            String format1 = sdf2.format(new Date());

            System.out.println("src/pic/" + format + format1 + ".png");
            FileUtils.copyFile(f, new File("src/pic/" + format + "/" + format1 + ".png"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    void getScreenshot(WebDriver driver) {
        try {
            File f = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf2 = new SimpleDateFormat("HH-mm-ss-SS");

            String format = sdf.format(new Date());
            String format1 = sdf2.format(new Date());

            System.out.println("src/pic/" + format + format1 + ".png");
            FileUtils.copyFile(f, new File("src/pic/" + format + "/" + format1 + ".png"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    //获取标签内容
    public void gerTexts() throws InterruptedException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss:SS");

        //无头方式运行
        WebDriver driver = driverConfig.getChromeDriver(List.of("--headless"));

        driver.manage().window().minimize();

        driver.get("https://www.baidu.com");

        //显示等待
//        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(2));

//        wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#hotsearch-content-wrapper > li:nth-child(1) > a")));

        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

//        WebElement element = driver.findElement(By.cssSelector("#hotsearch-content-wrapper > li:nth-child(1) > a"));
//        WebElement element = driver.findElement(By.cssSelector("#hotsearch-content-wrapper"));

//        System.out.println("text = " + element.getText());

//        //*[@id="hotsearch-content-wrapper"]
//        List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"hotsearch-content-wrapper\"]/li"));
        List<WebElement> elementW = driver.findElements(By.xpath("//*[@id=\"hotsearch-content-wrapper\"]/li/a"));

//        for(WebElement ele : elements){
//            System.out.println("text = " + ele.getText());
//            System.out.println("ele = " + ele);
//        }
        for (WebElement ele : elementW) {
            System.out.println("text = " + ele.getText());
            System.out.println("href = " + ele.getAttribute("href"));
        }


        Thread.sleep(100);

        getScreenshot(driver);

        driver.quit();
    }

    //切换窗口
    public void switchWindow() {
        WebDriver driver = driverConfig.getChromeDriver();
        try {
//          智能等待  隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));

            driver.get("https://www.baidu.com");

            driver.findElement(By.xpath("//*[@id=\"s_new_search_guide\"]/div/a/div[3]")).click();

            //切换控制的窗口
            String windowHandle = driver.getWindowHandle();

            Set<String> windowHandles = driver.getWindowHandles();
            for (String windowHandle2 : windowHandles) {
                if (!windowHandle.equals(windowHandle2)) {
                    driver.switchTo().window(windowHandle2);
                }
            }

            Thread.sleep(3000);

            //关闭当前控制的窗口
            driver.close();

        } catch (Exception e) {
            driver.quit();
        }
    }


    public void writePic() {
        WebDriver driver = driverConfig.getChromeDriver();

        try {
            driver.get("https://www.baidu.com");

            driver.findElement(By.xpath("//*[@id=\"s_new_search_guide\"]/div/a/div[3]")).click();

            driver.findElement(By.xpath("//*[@id=\"chat-input-main\"]/div[4]/div[1]")).sendKeys("画一张美女");

            driver.findElement(By.xpath("//*[@id=\"kw\"]")).click();
        } catch (Exception e) {
            driver.quit();
        }
    }


    public void select() throws IOException, InterruptedException {
        WebDriverManager.chromedriver().setup();

        ChromeOptions options = new ChromeOptions();

        options.addArguments("--remote-allow-origins=*");

        WebDriver driver = new ChromeDriver(options);

//        https://cn.bing.com/?scope=web

        driver.get("https://www.baidu.com");

        driver.manage().window().setSize(new Dimension(1444, 784));

        System.out.println("当前url" + driver.getCurrentUrl());
        System.out.println("title= " + driver.getTitle());

        driver.findElement(By.xpath("//*[@id=\"kw\"]")).sendKeys("top1美女");

//        driver.findElement(By.cssSelector("#")).click();
        driver.findElement(By.xpath("//*[@id=\"kw\"]")).click();

        driver.findElement(By.xpath("/html/body/div[1]/div[1]/div[6]/div[2]/div/form/span[2]/input")).click();

        Thread.sleep(1000);
        File f = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(f, new File("test.png"));

        driver.quit();
    }


    public void chrome() throws MalformedURLException {
        WebDriverManager.chromedriver().setup();

        ChromeOptions options = new ChromeOptions();

        options.addArguments("--remote-allow-origins=*");

        WebDriver driver = new ChromeDriver(options);

        driver.get("https://www.baidu.com");
        driver.findElement(By.xpath("//*[@id=\"kw\"]")).sendKeys("迪丽热巴");
        driver.findElement(By.xpath("//*[@id=\"kw\"]")).click();

    }

    public void edge() throws MalformedURLException {
//        WebDriverManager.edgedriver().setup();
//        System.setProperty("wdm.driverRepositoryUrl", "https://npm.taobao.org/mirrors/edgedriver");

//        String actualValue = System.getProperty("wdm.driverRepositoryUrl");
//        System.out.println("当前 wdm.driverRepositoryUrl 属性值: " + actualValue);


        //下载不了 他说 msedgedriver.azureedge.net 这个访问不了
//        io.github.bonigarcia.wdm.config.WebDriverManagerException: java.net.UnknownHostException: msedgedriver.azureedge.net

        System.setProperty("webdriver.edge.driver", "C:\\Users\\15328\\.cache\\selenium\\edgedriver_win64\\138.0.3351.95\\msedgedriver.exe");
//        WebDriverManager.edgedriver().setup();

        EdgeOptions edgeOptions = new EdgeOptions();

        edgeOptions.addArguments("--remote-allow-origins=*");

        WebDriver driver = new EdgeDriver(edgeOptions);

        driver.get("https://www.baidu.com");
        driver.findElement(By.xpath("//*[@id=\"kw\"]")).sendKeys("迪丽热巴");
        driver.findElement(By.xpath("//*[@id=\"kw\"]")).click();

    }
}


